//
// Created by zhengjuping on 24-7-10.
//

#include <driver/i2c.h>
#include <esp_log.h>
#include "include/SHT30.h"

#define I2C_MASTER_NUM              0
#define ACK_CHECK_EN                0x1                        /*!< I2C master will check ack from slave*/
#define ACK_VAL                     0x0                             /*!< I2C ack value */
#define NACK_VAL                    0x1                            /*!< I2C nack value */

#define SHT30_I2C_ADDR              0x44

#define TAG "SHT30"

int32_t SHT30::getValue(float &temperature, float &humidity) {
    uint8_t sht30Data[6]{};
    //获取温度 SHT30
    i2c_cmd_handle_t cmdHandle = i2c_cmd_link_create();
    i2c_master_start(cmdHandle);
    i2c_master_write_byte( cmdHandle, (SHT30_I2C_ADDR << 1) | I2C_MASTER_WRITE, ACK_CHECK_EN );
    i2c_master_write_byte( cmdHandle, 0x2C, ACK_CHECK_EN );
    i2c_master_write_byte( cmdHandle, 0x06, ACK_CHECK_EN );
    i2c_master_stop(cmdHandle);
    esp_err_t ret = i2c_master_cmd_begin((i2c_port_t)I2C_MASTER_NUM, cmdHandle, 1000 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmdHandle);

    vTaskDelay(100 / portTICK_PERIOD_MS);

    cmdHandle = i2c_cmd_link_create();
    i2c_master_start(cmdHandle);
    i2c_master_write_byte( cmdHandle, (SHT30_I2C_ADDR << 1) | I2C_MASTER_READ, ACK_CHECK_EN );
    i2c_master_read(cmdHandle, sht30Data, 6, I2C_MASTER_LAST_NACK);
    i2c_master_stop(cmdHandle);
    ret = i2c_master_cmd_begin((i2c_port_t)I2C_MASTER_NUM, cmdHandle, 1000 / portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmdHandle);

    temperature = (float )((((sht30Data[0] * 256.0) + sht30Data[1]) * 175) / 65535.0) - 45;
    humidity    = (float )((((sht30Data[3] * 256.0) + sht30Data[4]) * 100) / 65535.0);
    return 0;
}
